//! @Author: DengLibin
//! @Date: Create in 2024-07-17 12:28:05
//! @Description:
//!

use log::{error, info};
use rust_my_tools::apps::{
    dong_tai_data, migration_ai_paragraph, ribao_json, store_vec_data, tian_fu_mongo,
};
use rust_my_tools::dao::{copy_310_data, sqlserver2sqlite};
use rust_my_tools::{
    app::{self},
    apps::hubei_data_parse,
    sys::{
        self,
        global::{to_global_result, GlobalResult},
    },
    web,
};
use std::{env, net::SocketAddr};
use tokio::runtime::Builder;

fn cre_runtime(max_blocking_treads: usize) -> tokio::runtime::Runtime {
    // 创建一个 Tokio 运行时，配置线程池的大小
    Builder::new_multi_thread()
        //.worker_threads(1) // 设置工作线程的数量
        .max_blocking_threads(max_blocking_treads) // 设置阻塞任务的最大线程数
        .enable_all()
        .build()
        .unwrap()
}

/// @Author: DengLibin
/// @Date: Create in 2024-07-17 14:15:18
/// @Description: 启动应用
async fn start_web() -> sys::global::GlobalResult<()> {
    //初始化
    let app_state = app::init().await?;
    let (app_sate_arc, router) = web::router::new(app_state).await?;

    // run it
    let port = app_sate_arc.app_config.port as u16;
    let addr = SocketAddr::from(([0, 0, 0, 0], port));
    info!("====================================>监听端口:{}", addr);

    let listener = to_global_result(tokio::net::TcpListener::bind(addr).await)?;
    to_global_result(axum::serve(listener, router).await)
}

//启动web应用
#[allow(dead_code)]
fn async_run_web() -> GlobalResult<()> {
    // 创建一个 Tokio 运行时，配置线程池的大小
    let runtime = cre_runtime(16);
    runtime.block_on(start_web())
}

async fn hubei_data() -> GlobalResult<()> {
    // 获取所有命令行参数
    let args: Vec<String> = env::args().collect();
    // let r =hubei_data_parse::deal_file_path_dic("file_path", 0).await;
    if args.len() != 3 {
        println!("参数不正确");
        return Ok(());
    }
    let table_name = &args[1]; //"file_path"
    let start_id = args[2].parse::<i64>().unwrap();
    let r = hubei_data_parse::deal_file_path_dic(table_name, start_id).await;
    if let Err(e) = r {
        log::error!("异常了:{:?}", e);
    }
    Ok(())
}

/// @Author: DengLibin
/// @Date: Create in 2025-02-07 12:19:59
/// @Description: 一些应用
async fn start_app() -> GlobalResult<()> {
    app::init_log().await?;
    //info!("日志初始化完成");
    //----------------------------------------------------------------------------------------------//

    //导出文件列表
    // let r = apps::store_file_record::start().await;
    //----------------------------------------------------------------------------------------------//

    //下载附件
    //let r = apps::down_file_record::start(r"file_record.db").await;
    //----------------------------------------------------------------------------------------------//

    //湖北数据处理
    //hubei_data().await
    //----------------------------------------------------------------------------------------------//

    //动态数据导入
    // dong_tai_data::import_from_excel(r"C:\Users\denglibin\Desktop\测试数据1\资源.xlsx").await
    //dong_tai_data::import_from_excel2(r"C:\Users\denglibin\Desktop\测试数据2\资源.xlsx").await

    //----------------------------------------------------------------------------------------------//

    //310 sqlserver数据导出到sqlite
    // args() 返回一个迭代器，第一项是程序本身的路径
    // let args: Vec<String> = env::args().collect();
    // if args.len() < 2 {
    //     error!("参数错误，请指定表名");
    //     return Ok(());
    // }
    // copy_310_data::copy_to_sqlite(args.get(1).unwrap().as_str(), u32::MAX as usize).await
    //

    //----------------------------------------------------------------------------------------------//

    //检查es不存在文件数量
    /*
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        error!("参数错误");
        return Ok(());
    }
    let xxzx_id = args.get(1).unwrap().parse::<i64>()?;
    copy_310_data::check_es_data_files(xxzx_id).await
    */

    // copy_310_data::get_file_path().await

    //-----------------------------------检查在库里面不存在的附件-----------------------------------------------------------//

    // let args: Vec<String> = env::args().collect();
    // if args.len() < 2 {
    //     error!("参数错误");
    //     return Ok(());
    // }
    // let dir = args.get(1).unwrap();
    // copy_310_data::check_file_exists(dir).await
    //
    //--------------------------------------检查库里面重复的附件--------------------------------------------------------//

    // copy_310_data::check_es_repeat_files().await

    //----------------------------------------------------------------------------------------------//

    //ribao_json::json2sql().await

    //-------------------------------------------------------------------------------------------//
    // store_vec_data::start().await

    //--------------------------------------天府融媒mongodb----------------------------------------------------

    //mongodb到mysql
    let r = tian_fu_mongo::get_data().await;
    to_global_result(r)

    // tian_fu_mongo::mysql2sqlite().await

    //-------------------------------------迁移ai_paragraph_vec----------------------------------------------------
    // let r = migration_ai_paragraph::migrate_data().await;
    // to_global_result(r)
}
pub fn async_start_app() -> GlobalResult<()> {
    // 创建一个 Tokio 运行时，配置线程池的大小
    let runtime = cre_runtime(16);
    runtime.block_on(start_app())
}

pub fn main() {
    // do_some_work();

    // async_run_web().unwrap();
    async_start_app().unwrap();
}

// @Author: DengLibin
// @Date: Create in 2024-07-18 09:07:23
// @Description:
// #[tokio::main]创建的是多线程runtime，还有以下几种方式创建多线程runtime：
// #[tokio::main(flavor = "multi_thread"] // 等价于#[tokio::main]
// #[tokio::main(flavor = "multi_thread", worker_threads = 10)]
// #[tokio::main(worker_threads = 10))]

// #[tokio::main]
// async fn main() -> sys::global::GlobalResult<()> {
//     start_web().await
// }
